package mi.payment.ui.other;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.RemoteException;
import android.view.View;

import java.util.List;

import lainey.ui.dialog.IconHintDialog;
import lainey.ui.widget.TitleView;
import mi.payment.R;
import mi.payment.bean.db.TradeData;
import mi.payment.ui.print.helper.TotalSettlementDetail;
import mi.payment.constants.Params;
import mi.payment.controller.BaseSettlementResetTableController;
import mi.payment.controller.SettlementResetTableController;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.LastBatchTransDataOperation;
import mi.payment.settings.SettlementTransactionOperation;
import mi.payment.ui.base.ParentActivity;
import mi.payment.ui.print.BasePrintCallback;
import mi.payment.ui.print.helper.BasePrintController;
import mi.payment.utils.print.DataPrinterKernel;
import mi.payment.utils.transaction.ParamsInitTask;
import mi.payment.utils.transaction.SignOutTask;
import sunmi.payment.L3.L3BroadcastHelper;
import sunmi.payment.ui.dialog.LoadDialog;
import woyou.aidlservice.jiuiv5.ICallback;

/**
 * 结算结果页
 */
public class SettlementResultActivity extends ParentActivity {

    private List<PayDetail> mTransDetailList;
    private TotalSettlementDetail mTotalSettlementDetail;

    private BasePrintController mController;

    private IconHintDialog mIconHintDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settlement_result);
        initView();
        resetSettlementTable();
        if (Params.sL3Params == null || Params.sL3Params.isPrintTicket) {
            printTotalSettlementDetail();
        }
    }

    private void initView() {
        TitleView titleView = findViewById(R.id.title_view);
        titleView.setCenterText(R.string.settlement_result);
        titleView.setLeftImageVisibility(View.GONE);

        findViewById(R.id.mb_ok).setOnClickListener(
                v -> settlementConfirm()
        );

        mController = new BasePrintController(this);
        mController.initPrintData();
        // 初始化结算总计数据
        mTotalSettlementDetail = mController.getTotalSettlementDetail();
        // 初始化交易明细数据
        mTransDetailList = mController.getTransactionDetails();
        // 保存本批次的结算明细数据
        LastBatchTransDataOperation.getInstance().saveLastBatchTotalSettlementDetail(mTotalSettlementDetail);
        // 保存本批次的交易明细数据
        LastBatchTransDataOperation.getInstance().saveLastBatchTransDetails(mTransDetailList);
    }

    private void resetSettlementTable() {
        BaseSettlementResetTableController settlementResetTableController = new SettlementResetTableController();
        settlementResetTableController.resetSettlementTable();
    }

    @Override
    public void onBackPressed() {
        settlementConfirm();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissIconHintDialog();
    }

    private void printTotalSettlementDetail() {
        try {
            int printStatus = DataPrinterKernel.INSTANCE().updatePrinterState();
            if (printStatus == 1) {
                // 打印结算总计单
                mController.printTotalSettlementDetail(mCallback);
            } else {
                showToast(R.string.error_printer);
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast(R.string.error_printer);
        }
    }

    private ICallback mCallback = new BasePrintCallback() {

        @Override
        public void onPrintResult(final int code, String msg) throws RemoteException {
            runOnUI(
                    () -> {
                        if (code == 0) {
                            showPrintDialog();
                        }
                    }
            );
        }

    };

    /**
     * 结算确认按钮的点击事件处理
     */
    public void settlementConfirm() {
        // 得到缓存是否自动签退
        boolean autoSignOut = SettlementTransactionOperation.getInstance().getIsAutomaticSignOut();
        if (ParamsInitTask.isChecked && autoSignOut) {
            forceSignOut();
        } else {
            if (Params.sL3Params != null) {
                handleCallL3();
            } else {
                finish();
            }
        }
    }

    private void handleCallL3() {
        if (Params.sL3Params.isSettlementDetail) {
            List<PayDetail> detailList = mTransDetailList;
            L3BroadcastHelper.sendSettlementBroadcast(this, mTotalSettlementDetail, detailList);
        } else {
            L3BroadcastHelper.sendSettlementBroadcast(this, mTotalSettlementDetail);
        }
        sendCloseAppBroadcast();
        finish();
    }

    /**
     * 强制签退
     */
    @SuppressLint("StaticFieldLeak")
    private void forceSignOut() {
        TradeData tradeData = Params.newTradeData();
        SignOutTask task = new SignOutTask(this) {

            @Override
            protected void onPostExecuteImpl(TradeData tradeData) {
                finish();
            }

        };
        LoadDialog dialog = getLoadingDialog(R.string.sign_out);
        task.setLoadDialog(dialog);
        task.execute(tradeData);
    }


    private void showPrintDialog() {
        if (mIconHintDialog == null) {
            mIconHintDialog = new IconHintDialog(this);
            mIconHintDialog.setRightText(R.string.ok);
            mIconHintDialog.setLeftText(R.string.cancel);
            mIconHintDialog.setMessage(R.string.settlement_detail);
            mIconHintDialog.setIconResource(R.drawable.state_warning);
            mIconHintDialog.setLeftOnClickListener(
                    v -> dismissIconHintDialog()
            );
            mIconHintDialog.setRightOnClickListener(
                    v -> {
                        dismissIconHintDialog();
                        printTransactionDetail();
                    }
            );
            mIconHintDialog.setCancelable(true);
            mIconHintDialog.setCanceledOnTouchOutside(true);
        }
        try {
            mIconHintDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dismissIconHintDialog() {
        if (mIconHintDialog != null) {
            try {
                mIconHintDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void printTransactionDetail() {
        try {
            int printStatus = DataPrinterKernel.INSTANCE().updatePrinterState();
            if (printStatus == 1) {
                // 打印交易明细
                mController.printTransactionDetail(null);
            } else {
                showToast(R.string.error_printer);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
            showToast(R.string.error_printer);
        }
    }


}
